package my.engine.core;

import javax.servlet.*;
import java.io.IOException;
import java.util.List;

/**
 * User: emikolenko
 * Date: 24.03.2008
 * Time: 15:46:06
 */
public class MessageFilter implements Filter {

    private static ThreadLocal<List<String>> errors;
    private static ThreadLocal<List<String>> messages;

    public void init(FilterConfig filterConfig) throws ServletException {
        errors = new ThreadLocal<List<String>>();
        messages = new ThreadLocal<List<String>>();
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setAttribute("errors", errors.get());
        servletRequest.setAttribute("messages", messages.get());
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            errors.remove();
        }
    }

    public void destroy() {
        errors = null;
        messages = null;
    }

    public static ThreadLocal<List<String>> getErrors() {
        return errors;
    }

    public static void addError(String error) {
        errors.get().add(error);
    }

    public static ThreadLocal<List<String>> getMessages() {
        return messages;
    }

    public static void addMessage(String message) {
        messages.get().add(message);
    }
}
